package com.google.project.client.Sharing;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Admin.ADMEntrypoint;
import com.google.project.client.Director.DRTEntrypoint;
import com.google.project.client.HumanResources.HMEntrypoint;
import com.google.project.client.Operator.OPTEntrypoint;
import com.google.project.client.ProjectManager.PMEntrypoint;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.MessageService;
import com.google.project.client.Service.MessageServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.MessageDTO;
import com.google.project.shared.UsersDTO;
import com.google.gwt.event.dom.client.ChangeEvent;

public class MessageList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Button btnSearch;
	@UiField TextBox txtSenderUserName;
	@UiField TextBox txtSubject;
	@UiField ListBox cboStatus;
	@UiField SimplePager pager;
	@UiField(provided = true) CellTable<MessageDTO> ctbMessageList = new CellTable<MessageDTO>();
	@UiField ListBox cboCate;
	@UiField Button btnCreateMessage;

	private final LoginServiceAsync loginService = GWT.create(LoginService.class);
	private final MessageServiceAsync messageService = GWT.create(MessageService.class);
	List<MessageDTO> listMessage = new ArrayList<MessageDTO>();
	UsersDTO userDTO = new UsersDTO();
	MessageDTO messDTO = new MessageDTO();

	interface Binder extends UiBinder<Widget, MessageList> {
	}

	public MessageList() {
		initWidget(binder.createAndBindUi(this));
		getInfoUserLogin();
		initTable();
		initData();
	}

	// get info user login from session
	public void getInfoUserLogin() {
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(UsersDTO result) {
				userDTO = result;
			}
		});
	}

	// init data to combobox
	public void initData() {
		cboCate.addItem("---Tất cả---", "-1");
		cboCate.addItem("Đã nhận", "0");
		cboCate.addItem("Đã gửi", "1");

		// init cbStatus
		cboStatus.addItem("---Tất cả---", "-1");
		cboStatus.addItem("Chưa đọc", "1");
		cboStatus.addItem("Đã đọc", "0");

		// get all message
		getAllMess();
	}

	// init table
	public void initTable() {
		TextColumn<MessageDTO> stt = new TextColumn<MessageDTO>() {
			@Override
			public String getValue(MessageDTO mess) {
				return mess.getIndex();
			}
		};

		// sender
		TextColumn<MessageDTO> senderColumn = new TextColumn<MessageDTO>() {
			@Override
			public String getValue(MessageDTO mess) {
				return mess.getSenderName();
			}
		};
		// subject
		Column<MessageDTO, String> subjectColumn = new Column<MessageDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(MessageDTO mess) {
				return mess.getSubject();
			}
		};
		subjectColumn.setFieldUpdater(new FieldUpdater<MessageDTO, String>() {

			@Override
			public void update(int index, MessageDTO mess, String value) {
				messDTO = mess;
				// khi click vao tin nhan moi thi doi trang thai status=0 (tru
				// truong hop thu da gui?)
				int status = 0;
				if (!cboCate.getValue(cboCate.getSelectedIndex())
						.equalsIgnoreCase("1")) {
					messageService.updateParentMess(mess.getId(), status,
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onSuccess(Void result) {
									if (userDTO.getUserGroup() == 1) {
										DRTEntrypoint.get().DRTMessDetail(messDTO);
									} else if (userDTO.getUserGroup() == 2) {
										PMEntrypoint.get().PMMessageDetail(messDTO);
									} else if (userDTO.getUserGroup() == 3) {
										OPTEntrypoint.get().OPTMessageDetail(messDTO);
									} else if (userDTO.getUserGroup() == 4) {
										HMEntrypoint.get().HMMessDetail(messDTO);
									} else if (userDTO.getUserGroup() == 6) {
										ADMEntrypoint.get().ADMMessDetail(messDTO);
									}
								}
							});

				} else {
					if (userDTO.getUserGroup() == 1) {
						DRTEntrypoint.get().DRTMessDetail(messDTO);
					} else if (userDTO.getUserGroup() == 2) {
						PMEntrypoint.get().PMMessageDetail(messDTO);
					} else if (userDTO.getUserGroup() == 3) {
						OPTEntrypoint.get().OPTMessageDetail(messDTO);
					} else if (userDTO.getUserGroup() == 4) {
						HMEntrypoint.get().HMMessDetail(messDTO);
					} else if (userDTO.getUserGroup() == 6) {
						ADMEntrypoint.get().ADMMessDetail(messDTO);
					}
				}
			}

		});
		// created on date
		TextColumn<MessageDTO> dateColumn = new TextColumn<MessageDTO>() {
			@Override
			public String getValue(MessageDTO mess) {
				return CommonFuntion.convertToDate(new Date(mess.getCreatedOnDate()));
			}
		};
		ctbMessageList.setStyleName("ttable");
		ctbMessageList.addColumn(stt, "STT");
		ctbMessageList.addColumn(subjectColumn, "Tiêu Đề");
		subjectColumn.setCellStyleNames("celltable");
		ctbMessageList.setColumnWidth(subjectColumn, 48.0, Unit.PCT);
		ctbMessageList.getColumn(ctbMessageList.getColumnIndex(subjectColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbMessageList.addColumn(senderColumn, "Người Gửi");
		ctbMessageList.setColumnWidth(senderColumn, 20.0, Unit.PCT);
		ctbMessageList.getColumn(ctbMessageList.getColumnIndex(senderColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbMessageList.addColumn(dateColumn, "Ngày Gửi");
		ctbMessageList.setColumnWidth(dateColumn, 12.0, Unit.PCT);
		ctbMessageList.getColumn(ctbMessageList.getColumnIndex(dateColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
	}

	// fill data to celltable
	protected void loadData(List<MessageDTO> messList) {

		ListDataProvider<MessageDTO> dataProvider = new ListDataProvider<MessageDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbMessageList);

		// Add the data to the data provider, which automatically pushes it to
		// the widget

		List<MessageDTO> list = dataProvider.getList();
		int count = 1;
		for (MessageDTO mess : messList) {
			mess.setIndex(count + "");
			list.add(mess);
			count++;
		}
		pager.setDisplay(ctbMessageList);
	}

	// get all Message
	public void getAllMess() {
		messageService.getMessageList(new AsyncCallback<List<MessageDTO>>() {

			@Override
			public void onSuccess(List<MessageDTO> result) {
				for (MessageDTO messageDTO : result) {
					listMessage.add(messageDTO);
				}
				LoadMess();
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}

	// get Message where (userId=receiveId and status=1) or (userId=senderId and
	// status=2) & parentID=0
	private void LoadMess() {
		Boolean condition = true;
		List<MessageDTO> temple = new ArrayList<MessageDTO>();

		for (MessageDTO mess : listMessage) {
			condition = condition && (mess.getTypeId()==1)
					&& (mess.getParentId().equalsIgnoreCase("0") && (((mess
							.getStatus() == 1)
							&& mess.getReceiverId().equals(userDTO.getUserId()) || ((mess
							.getStatus() == 2) && mess.getSenderId().equals(
							userDTO.getUserId())))));
			if (condition) {
				temple.add(mess);
			}
			condition = true;
		}
		if (temple != null) {
			loadData(temple);
		}
	}

	// Ham search
	private void searchFunction() {
		String senderName = txtSenderUserName.getText().trim();
		String subject = txtSubject.getText().trim();
		Boolean condition = true;
		List<MessageDTO> temple = new ArrayList<MessageDTO>();
		for (MessageDTO mess : listMessage) {

			if (senderName != null && !senderName.equalsIgnoreCase("")) {
				condition = condition
						&& (mess.getSenderName().contains(senderName));
			}
			if (subject != null && !subject.equalsIgnoreCase("")) {
				condition = condition && (mess.getSubject().contains(subject));
			}
			if ((cboCate.getValue(cboCate.getSelectedIndex()) != null && userDTO.getUserId() != null)) {
				String value = cboCate.getValue(cboCate.getSelectedIndex());
				if (value.equalsIgnoreCase("0")) {
					condition = condition
							&& (mess.getReceiverId()
									.equals(userDTO.getUserId()));
				} else if (value.equalsIgnoreCase("1")) {
					condition = condition
							&& (mess.getSenderId().equals(userDTO.getUserId()));
				}
			}
			if ((cboStatus.getValue(cboStatus.getSelectedIndex())) != null
					&& !cboStatus.getValue(cboStatus.getSelectedIndex())
							.equalsIgnoreCase("-1")) {
				int status = Integer.parseInt((cboStatus.getValue(cboStatus
						.getSelectedIndex())));
				if (status == 0) {
					condition = condition && (mess.getStatus() == 0);
				} else if (status == 1) {
					condition = condition && (mess.getStatus() == 1);
				}
			}
			if (condition && (mess.getTypeId()==1)  && (mess.getParentId().equalsIgnoreCase("0"))) {
				temple.add(mess);
			}
			condition = true;
		}
		if (temple != null) {
			loadData(temple);
		} else {
			Window.alert("Không tìm thấy dữ liệu");
			loadData(temple);
		}
	}

	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		searchFunction();
	}

	@UiHandler("btnCreateMessage")
	void onBtnCreateMessageClick(ClickEvent event) {
		if (userDTO.getUserGroup() == 1) {
			DRTEntrypoint.get().DRTCreateMessage();
		}
		else if (userDTO.getUserGroup() == 2) {
			PMEntrypoint.get().PMCreateMessage();
		} else if (userDTO.getUserGroup() == 3) {
			OPTEntrypoint.get().OPTCreateMessage();
		} else if (userDTO.getUserGroup() == 4) {
			HMEntrypoint.get().HMCreateMessage();
		}else if (userDTO.getUserGroup() == 6) {
			ADMEntrypoint.get().ADMCreateMessage();
		}

	}

	@UiHandler("cboCate")
	void onCboCateChange(ChangeEvent event) {
		if ((cboCate.getValue(cboCate.getSelectedIndex())) != null
				&& !cboCate.getValue(cboCate.getSelectedIndex())
						.equalsIgnoreCase("-1")) {
			int status = Integer.parseInt((cboCate.getValue(cboCate
					.getSelectedIndex())));
			if (status == 0) {
				cboStatus.setEnabled(true);
			} else if (status == 1) {
				cboStatus.setEnabled(false);
			}
		}
	}
}
